Ext.define('FSearchForm', {
    extend: 'FForm',
    alias: 'widget.fsearchform',
    
    /**
     * Nome da classe que controla o formulário.
    */
    className: 'FDefaultController',
    
    /**
     * storeParam: informa a ação que a classe deverá tomar para retornar os dados.
     */
    storeParam: 'search',
    
    /**
     * Formulário de inserção relacionado a este form de busca.
     */
    insertForm: 'FEditForm',
    
    /**
     * Formulário de edição relacionado a este form de busca.
     */
    editForm: 'FEditForm',
    
    // Maximizado?
    maximized: true,
    
    // Campos do form.
    formFields: null,
    
    // Grid do form
    formGrid: null,
    
    /**
     * Configuração das colunas da grid. REQUIRED.
     * Ex.: [{text: 'Código', flex: 1, visible: false}, {text: 'Nome', flex: 3, visible: true}]
     */
    gridColumnsConfig: null,
    
    /**
     * Campos do store (que retornam da consulta do servidor) - Array de strings.
     * Devem coincidir com as colunas da grid.
     * Ex.: ['codigo', 'nome']
     * REQUIRED.
     */
    storeFields: null,
    
    // Número de registros por página da grid
    pageSize: 1000,
    
    /**
     * Nome do campo identificador. Default 'id'.
     */
    idxName: 'id',
    
    // PRIVATE
    gridColumns: null,
    searchFields: null,
    
    initComponent: function()
    {        
        this.searchFields = this.formFields;
        
        var padding = '10 10 10 200';
        if ( this.isLookupFieldForm )
        {
            padding = '10 10 10 10';
        }
        
        var fieldSet = new Ext.form.FieldSet({
            baseCls: 'x-fieldset-noborder',
            padding: padding,
            items: this.formFields
        });
        
        this.formPanel = new Ext.form.FormPanel({
            layout: 'form',
            cls: 'form',
            baseCls: 'x-fieldset-noborder',
            padding: '8px',
            items: fieldSet
        });

        var store = Ext.create('Ext.data.JsonStore',
        {
            pageSize: this.pageSize,
            proxy: {
                type: 'ajax',
                url: this.handlerUrl,
                actionMethods: 'POST',
                reader: {
                    type: 'json',
                    root: 'data'
                },
                extraParams: {
                    manager: this.className,
                    action: this.storeParam,
                    table: this.table
                },
                noCache: false
            },
            fields: this.storeFields,
            totalProperty: 'total'
        });
        
        this.gridColumns = {
            items: [],
            defaults: {
                align: 'center',
                sortable: true,
                hideable: true
            }
        };

        if ( this.storeFields.length != this.gridColumnsConfig.length )
        {
            if ( this.isLookupFieldForm )
            {
                this.gridColumns.items.push({
                    xtype: 'actioncolumn',
                    width: 30,
                    items: [{
                        tootltip: 'Selecionar',
                        icon: 'themes/default/images/select.png',
                        scope: this,
                        handler: function(grid, rowIndex, colIndex) {
                            this._onBtnSelectRow(rowIndex, colIndex);
                        }
                    }]
                });
            }
            
            for(var i = 0; i < this.storeFields.length; i++ )
            {
                this.gridColumns.items.push({
                    text: this.storeFields[i],
                    dataIndex: this.storeFields[i]
                });
            }
        }
        else
        {
            if ( this.isLookupFieldForm )
            {
                this.gridColumns.items.push({
                    xtype: 'actioncolumn',
                    width: 30,
                    items: [{
                        tooltip: 'Selecionar',
                        icon: 'themes/default/images/select.png',
                        scope: this,
                        handler: function(grid, rowIndex, colIndex) {
                            this._onBtnSelectRow(rowIndex, colIndex);
                        }
                    }]
                });
            }
            
            for(var i = 0; i < this.storeFields.length; i++ )
            {
                this.gridColumns.items.push({
                    text: this.gridColumnsConfig[i].text,
                    flex: this.gridColumnsConfig[i].flex,
                    align: this.gridColumnsConfig[i].align,
                    sortable: this.gridColumnsConfig[i].sortable,
                    hideable: this.gridColumnsConfig[i].hideable,
                    width: this.gridColumnsConfig[i].width,
                    hidden: !this.gridColumnsConfig[i].visible,
                    dataIndex: this.storeFields[i]
                });
            }
        }
        
        this.formGrid = Ext.create('FGrid',
        {
            store: store,
            columns: this.gridColumns,
            pageSize: this.pageSize
        });
        
        var searchButtons = [
            Ext.create('FButton', {
                text: 'Limpar',
                width: 100,
                iconCls: 'button-clear',
                scope: this,
                handler: this._onBtnClearClick
            }),
            Ext.create('FButtonOk', {
                text: 'Aplicar',
                width: 100,
                scope: this,
                handler: this._onBtnApplyClick
            })            
        ];
        
        var insert = false;
        var update = false;
        var del = false;
        
        this.tbar = [            
            {
                text: 'Inserir',
                iconCls: 'button-insert',
                iconAlign: 'top',
                scope: this,
                handler: this._onBtnInsertClick,
                hidden: insert
            },

            {
                text: 'Editar',
                iconCls: 'button-update',
                iconAlign: 'top',
                scope: this,
                handler: this._onBtnEditClick,
                hidden: update
            },

            {
                text: 'Excluir',
                iconCls: 'button-delete',
                iconAlign: 'top',
                scope: this,
                handler: this._onBtnDeleteClick,
                hidden: del
            },

            {
                text: 'Fechar',
                iconCls: 'button-exit',
                iconAlign: 'top',
                scope: this,
                handler: this._onBtnCloseClick
            }
        ];
        
        this.formFields = [
            {
                xtype: 'panel',
                width: '100%',
                flex: 3,
                layout: 'fit',
                title: 'Campos da pesquisa',
                items: this.formPanel
            },
            {
                xtype: 'container',
                width: '100%',
                flex: 1,
                layout: {
                    type:'hbox',
                    padding: '5',
                    pack: 'center'
                },
                items: searchButtons
            },
            {
                xtype: 'panel',
                width: '100%',
                flex: 6,
                layout: 'fit',
                title: 'Resultados da pesquisa',
                items: this.formGrid
            }
        ];
        
        this.callParent();
    },
    _onBtnClearClick: function()
    {
        this.formPanel.getForm().reset();
    },
    _onBtnApplyClick: function()
    {
        var form = this.formPanel.getForm();

        this.el.mask('Pesquisando...');
                
        form.submit({
            url: this.handlerUrl,
            params: {
                manager: this.className,
                action: 'search',
                table: this.table,
                limit: this.pageSize
            },
            scope: this,
            success: function(form, action)
            {
                this.el.unmask();
                var obj = Ext.JSON.decode(action.response.responseText);
                
                if ( obj.empty )
                {
                    Ext.create('FMessageAlert', {
                        msg: obj.msg ? obj.msg : 'Não foram encontrados registros para a sua busca.'
                    }).show();
                }
                
                for (var count = 0; count < this.searchFields.length; count++)
                {
                    var value = document.getElementsByName(this.searchFields[count].name)[0].value;
                    this.formGrid.store.getProxy().setExtraParam(this.searchFields[count].name, value);
                }
                
                this.formGrid.store.reload();
                this.formGrid.store.loadRawData(obj);                
            },
            failure: function(form, action)
            {
                this.el.unmask();

                var obj = Ext.JSON.decode(action.response.responseText);
                this.formGrid.store.loadRawData(null);
                
                Ext.create('FMessage', {
                    msg: obj.msg ? obj.msg : 'Erro ao processar sua requisição.'
                }).show();
            }
        });
    },
    _onBtnDeleteClick: function()
    {
        var selecteds = this.formGrid.getSelectionModel().getSelection();
        var rows = selecteds.length;

        if( rows === 0 )
        {
            Ext.create('FMessageAlert', {
                msg: 'Nenhum registro selecionado!'
            }).show();
            
            return;
        }

        Ext.Msg.confirm('Confirmação', '<b>Deseja excluir estes registros?</b>', function(btn)
        {
            if( btn == 'yes' )
            {
                var counter = 0;
                var ids = new Array(rows);                
                while ( counter < rows )
                {
                    // Se idxName tiver vírgula, é porque é uma chave composta.        
                    if ( this.idxName.match(/,/g) )
                    {
                        var indexes = this.idxName.split(",");
                        var values = new Array(indexes.length);

                        for ( var i = 0; i <= indexes.length; i++ )
                        {
                            values[i] = selecteds[counter].get(indexes[i]);
                        }

                        ids[counter] = values;
                    }
                    else
                    {
                        ids[counter] = selecteds[counter].get(this.idxName);                        
                    }
                    
                    counter++;
                }

                this.el.mask('Excluindo...');

                Ext.Ajax.request(
                {
                    url: this.handlerUrl,
                    params: {
                        manager: this.className,
                        action: 'delete',
                        table: this.table,
                        'rows[]': ids,
                        idxName: this.idxName
                    },
                    scope: this,
                    success: function(response, opts)
                    {
                        this.el.unmask();

                        var obj = Ext.decode(response.responseText);
                        if ( obj.success )
                        {
                            this.formGrid.store.remove(selecteds);
                        }

                        Ext.create('FMessageSuccess', {
                            msg: obj.msg
                        }).show();
                    },
                    failure: function(response, opts)
                    {
                        this.el.unmask();

                        var obj = Ext.decode(response.responseText);
                        
                        Ext.create('FMessageError', {
                            msg: obj.msg
                        }).show();
                    }
                });
            }
        }, this);
    },
    _onBtnInsertClick: function()
    {
        Ext.create(this.insertForm, {
            handlerUrl: this.handlerUrl,
            className: this.className,
            table: this.table
        }).show();
    },
    _onBtnEditClick: function()
    {
        var selecteds = this.formGrid.getSelectionModel().getSelection();
        var rows = selecteds.length;

        if( rows === 0 )
        {
            Ext.create('FMessageAlert', {
                msg: 'Nenhum registro selecionado!'
            }).show();
            
            return;
        }

        if ( rows > 1 )
        {
            Ext.create('FMessageAlert', {
                msg: 'Selecione apenas um registro para edição!'
            }).show();

            return;
        }

        // Se idxName tiver vírgula, é porque é uma chave composta.        
        if ( this.idxName.match(/,/g) )
        {
            var indexes = this.idxName.split(",");
            var ids = new Array(indexes.length);
            
            for ( var i = 0; i <= indexes.length; i++ )
            {
                ids[i] = selecteds[0].get(indexes[i]);
            }
            
            Ext.create(this.editForm, {
                formAction: 'update',
                handlerUrl: this.handlerUrl,
                table: this.table,
                className: this.className,
                dataId: ids.join(","),
                idxName: this.idxName
            }).show();
        }
        else
        {
            Ext.create(this.editForm, {
                formAction: 'update',
                handlerUrl: this.handlerUrl,
                table: this.table,
                className: this.className,
                dataId: selecteds[0].get(this.idxName),
                idxName: this.idxName
            }).show();
        }
    },
    _onBtnSelectRow: function(rowIndex, colIndex)
    {
        var selected = this.formGrid.getStore().getAt(rowIndex);

        this.idField.setValue(selected.get(this.idxName));
        this.idField.onBlur();
        
        this.doClose();
    }
});
